import * as Api from '../api/index';
import wxPromisify from "@/libs/wxPromisify";

let openId = '';

export default {
  checkLoginStatus() {
    return !!uni.getStorageSync('login_token');
  },
  getToken() {
    return uni.getStorageSync('login_token')
  },
  setToken(token) {
    return uni.setStorageSync('login_token', token);
  },
  setLoginType(type) {//设置登录类型，type:phone;wechat
    return uni.setStorageSync('login_type', type);
  },
  getLoginType() {//获取登录类型
    return uni.getStorageSync('login_type')
  },
  async login() {
    let {returnCode, resultData} = await Api.getAppletOpenId();
    if (returnCode === "0") {
      this.setToken(resultData.token);
      this.setLoginType("wechat");
    } else if (returnCode === "1") {
      openId = resultData.openId;
    }
    return {returnCode, resultData};
  },
  async bindAccount(code,openId) {
    let {returnCode, resultData} = await Api.authBindOpenId(code, openId);
    console.log('微信登录returnCode:',returnCode);
    console.log('微信登录resultData:',resultData);
    if (returnCode === "0") {
      this.setToken(resultData.token);
      this.setLoginType("wechat");
    }
    return {returnCode, resultData};
  },
  async loginByPhone(mobile, smscode){
    let {returnCode, resultData} = await Api.loginByPhone(mobile, smscode);
    console.log('手机号登录returnCode:',returnCode);
    console.log('手机号登录resultData:',resultData);
    if (returnCode === "0") {
      this.setToken(resultData.token);
      this.setLoginType("phone");
    }
    // uni.showToast(resultData);
    return {returnCode, resultData};
  },

  async appletsCheckPhoneToken(){
    let {returnCode, resultData} = await Api.appletsCheckPhoneToken(this.getToken());
    console.log('手机号token校验returnCode:',returnCode);
    console.log('手机号token校验resultData:',resultData);
    if (returnCode != "0") {
      // uni.removeStorageSync(this.getToken());//需要重新登录 把原来的token删除
      await wxPromisify.navigateTo({
        url: '/pages/login/index'
      })
    }
    return {returnCode, resultData};
  },

  async appletsCheckToken(){
    let {returnCode, resultData} = await Api.appletsCheckPhoneToken(this.getToken());
    console.log('有效token校验returnCode:',returnCode);
    console.log('有效token校验resultData:',resultData);
    return {returnCode, resultData};
  },


  async CheckLoginByCode() {//根据code获取openid，并查看业务员表中是否有该openid，有 说明登陆过，返回token
    let {returnCode, resultData} = await Api.CheckLoginByCode1();
    if (returnCode === "0") {
      this.setToken(resultData.token);
      this.setLoginType("admin");
    }
    return {returnCode, resultData};
  },

  async loginByAdmin(param){
    let {returnCode, resultData} = await Api.loginByAdmin1(param);
    console.log('业务员登录returnCode:',returnCode);
    console.log('业务员登录resultData:',resultData);
    if (returnCode === "0") {
      this.setToken(resultData.token);
      this.setLoginType("admin");
    }
    // uni.showToast(resultData);
    return {returnCode, resultData};
  },

}